package com.ruoyi.common.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.system.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MP注入处理器
 * mybatis plus 插入/更新自动填充
 *
 * @author fanglei
 * @date 2021/05/28 14:24
 **/
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {
    /**
     * mybatis plus 插入自动填充数据
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("开始插入填充...");
        if (metaObject.hasGetter("createTime"))
            this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
        if(SecurityUtils.getLoginUser()==null){
            return;//无登录的
        }
        LoginUser sysUser = SecurityUtils.getLoginUser();
        //2025-6-19 填充必填字段 改为空时才填充
        if (metaObject.hasGetter("createBy") && metaObject.getValue("createBy")==null)
            this.strictInsertFill(metaObject, "createBy", String.class, sysUser.getUserId().toString());
        if (metaObject.hasGetter("userId") && metaObject.getValue("userId")==null)
            this.strictInsertFill(metaObject, "userId", String.class, sysUser.getUserId().toString());
    }

    /**
     * mybatis plus 更新自动填充数据
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("开始更新填充...");
        if (metaObject.hasGetter("updateTime"))
            this.strictUpdateFill(metaObject, "updateTime", Date.class, DateUtils.getNowDate());
        if(SecurityUtils.getLoginUser()==null){
            return;//无登录的
        }
        LoginUser sysUser = SecurityUtils.getLoginUser();
        if (metaObject.hasGetter("updateBy"))
            this.strictUpdateFill(metaObject, "updateBy", String.class, sysUser.getUserId().toString());
    }
}
